

#include "shopscene.h"
#include "armiesscene.h"
#include "resourcemanager.h"
#include "log.h"
#include "messagequeue.h"
#include "gamemanager.h"
#include "gamedatamanager.h"
#include "cocos-ext.h"
#include "goldcoinscene.h"

static const int VIEW_MARGIN = 20;
static const int PACK_ITEM_WIDTH = 200;
static const int PACK_HEIGHT = 468;
static const int PACK_ITEM_SPACE = 40;

static const int EQUIPMENT_ITEM_WIDTH = 80;
static const int EQUIPMENT_ITEM_HEIGHT = 80;
static const int EQUIPMENT_ITEM_SPACE = 12;

static const int TAG_MASK_LAYER = 1000;

static float scales[] = {1.0f, 0.8f, 0.8f, 0.8f, 0.8f};

ShopScene::ShopScene():
_layer(nullptr)
, _selectedTabIndex(0)
, _touchedTabButtonIndex(-1)
, _touchedEquipmentIndex(-1) {
	memset(_arrSprites, (int) CardPackType::count, sizeof(_arrSprites));
}

ShopScene::~ShopScene() {
}

bool ShopScene::init() {
	if (!CCScene::init()) {
		return false;
	}

	_layer = CCLayer::create();
	_layer->setTouchEnabled(false);
	addChild(_layer);

	auto sceneBg = cocos2d::extension::CCScale9Sprite::create("textures/pad_bg.png", CCRectMake(0, 0, 225, 225), CCRectMake(100, 100, 25, 25));
	sceneBg->setContentSize(GM->screenSize);
	sceneBg->setPosition(CCPointZero);
	sceneBg->setAnchorPoint(ccp(0.0f, 0.0f));
	_layer->addChild(sceneBg);

	auto btnExit = RM->makeBackButton(this, menu_selector(ShopScene::onClose), _layer, false);
	btnExit->setPosition(XY_SCALE(45, 535));

	auto btnMoney = RM->makeButton("money_pad.png", nullptr, nullptr, this, menu_selector(ShopScene::onRecharge), _layer);
	btnMoney->setPosition(XY_SCALE(GameManager::BASE_WIDTH, GameManager::BASE_HEIGHT - 30));
	btnMoney->setAnchorPoint(ccp(1.0f, 0.5f));

	sprintf(buf, "%d", GDM->money);
	_labelMoney = CCLabelTTF::create(buf, "", 24);
	_labelMoney->setPosition(ccp(76, 30));
	_labelMoney->setColor(ccc3(237, 199, 143));
	_labelMoney->setAnchorPoint(ccp(0.5f, 0.5f));
	btnMoney->addChild(_labelMoney);

	int count = (int) CardPackType::count;
	CCSize packsViewSize = CCSizeMake((PACK_ITEM_WIDTH + PACK_ITEM_SPACE) * count - PACK_ITEM_SPACE, PACK_HEIGHT);
	_layerPacks = CCLayer::create();
	_layerPacks->setContentSize(packsViewSize);
	_layerPacks->setScale(GM->minscale);
	_layerPacks->setPosition(ccp(VIEW_MARGIN, VIEW_MARGIN));
	_layer->addChild(_layerPacks);

	static const char *CARD_ICONS[] = {
			"card_1.png", "card_1.png", "card_1.png", "card_1.png", "card_1.png", "card_1.png", "card_1.png", "card_1.png", "card_1.png",
	};

	float x = VIEW_MARGIN + PACK_ITEM_WIDTH / 2.0f;
	for (int i = 0; i < count; i++) {
		const CardPackInfo& info = GDM->packs[i];

		CCSprite *sprCard = MAKE_SPRITE(CARD_ICONS[i]);
		sprCard->setScale(1.0f);
		sprCard->setPosition(XY_SCALE(x, 350.0f));
		_layerPacks->addChild(sprCard);

		CCSprite *sprSalePad = MAKE_SPRITE("card_sale_pad.png");
		sprSalePad->setScale(1.0f);
		sprSalePad->setPosition(XY_SCALE(x, 140.0f));
		_layerPacks->addChild(sprSalePad);

		sprintf(buf, "%d", info.price);
		CCLabelTTF *labelPrice = CCLabelTTF::create(buf, "", 24);
		labelPrice->setPosition(ccp(90, 227));
		labelPrice->setAnchorPoint(ccp(0.0f, 0.5f));
		labelPrice->setColor(ccc3(253, 243, 37));
		sprSalePad->addChild(labelPrice);

		sprintf(buf, "x%d", info.legendary);
		CCLabelTTF *labelQuantity = CCLabelTTF::create(buf, "", 16);
		labelQuantity->setPosition(ccp(140, 195));
		labelQuantity->setAnchorPoint(ccp(0.0f, 0.5f));
		labelQuantity->setColor(ccc3(197, 116, 20));
		sprSalePad->addChild(labelQuantity);

		sprintf(buf, "x%d", info.rare);
		labelQuantity = CCLabelTTF::create(buf, "", 16);
		labelQuantity->setPosition(ccp(140, 160));
		labelQuantity->setAnchorPoint(ccp(0.0f, 0.5f));
		labelQuantity->setColor(ccc3(23, 95, 170));
		sprSalePad->addChild(labelQuantity);

		sprintf(buf, "x%d", info.uncommon);
		labelQuantity = CCLabelTTF::create(buf, "", 16);
		labelQuantity->setPosition(ccp(140, 125));
		labelQuantity->setAnchorPoint(ccp(0.0f, 0.5f));
		labelQuantity->setColor(ccc3(35, 142, 23));
		sprSalePad->addChild(labelQuantity);

		sprintf(buf, "x%d", info.common);
		labelQuantity = CCLabelTTF::create(buf, "", 16);
		labelQuantity->setPosition(ccp(140, 90));
		labelQuantity->setAnchorPoint(ccp(0.0f, 0.5f));
		labelQuantity->setColor(ccc3(0, 0, 0));
		sprSalePad->addChild(labelQuantity);

		auto button = RM->makeButton("button/blue_button_0.png", "button/blue_button_1.png", nullptr, this, menu_selector(ShopScene::onBuyPack), sprSalePad);
		button->setTag(100 + i);
		button->setPosition(ccp(97, 36));

		RM->makeButtonLabel("Buy", 20, button);

		x += PACK_ITEM_WIDTH + PACK_ITEM_SPACE;
	}

	return true;
}

bool ShopScene::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent) {
	auto pt = pTouch->getLocation();


	return true;
}

void ShopScene::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent) {
	auto pt = pTouch->getLocation();
	slidePacksView(pTouch->getDelta().x);
}

void ShopScene::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent) {
	auto pt = pTouch->getLocation();
}

void ShopScene::ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent) {
}

void ShopScene::onClose(CCObject *sender) {
	CCDirector::sharedDirector()->replaceScene(ArmiesScene::create());
}

void ShopScene::slidePacksView(float distance) {
	CCPoint newPt = _layerPacks->getPosition();
	newPt.x += distance;

	float minx = GM->screenSize.width - _layerPacks->getContentSize().width;
	if (newPt.x < minx) {
		newPt.x = minx;
	}
	if (newPt.x > VIEW_MARGIN) {
		newPt.x = VIEW_MARGIN;
	}

	_layerPacks->setPosition(newPt);
}

void ShopScene::keyBackClicked() {
	onClose(nullptr);
}

void ShopScene::keyMenuClicked() {

}

void ShopScene::onBuyPack(CCObject *sender) {
	int index = ((CCNode *) sender)->getTag() - 100;
	CardPackInfo info = GDM->packs[index];

	vector<string> equipmentsName;
	vector<int> equipmentsQuantity;

	time_t now = time(0);
	tm *t = localtime(&now);
	srand(t->tm_mday);

	CardPackType packType = (CardPackType) index;
	EquipmentType equipmentType = EquipmentType::count;

	switch (packType) {
		case CardPackType::today:
		case CardPackType::week: {
			int index = rand() % GDM->creatures.size();
			equipmentsName.push_back(GDM->creatures[index]);
			equipmentsQuantity.push_back(12);
			break;
		}
		case CardPackType::bronze:
		case CardPackType::silver:
		case CardPackType::gold:
			equipmentType = (EquipmentType) (rand() % ((int) EquipmentType::count));
		case CardPackType::weapon:
			if (equipmentType == EquipmentType::count) {
				equipmentType = EquipmentType::weapon;
			}
		case CardPackType::armor:
			if (equipmentType == EquipmentType::count) {
				equipmentType = EquipmentType::armor;
			}
		case CardPackType::shield:
			if (equipmentType == EquipmentType::count) {
				equipmentType = EquipmentType::shield;
			}
		case CardPackType::special: {
			if (equipmentType == EquipmentType::count) {
				equipmentType = EquipmentType::special;
			}

			int *arrQuantity[] = {&info.legendary, &info.rare, &info.uncommon, &info.common};
			EquipmentRarity arrRarity[] = {EquipmentRarity::legendary, EquipmentRarity::rare, EquipmentRarity::uncommon, EquipmentRarity::common};

			for (int i = 0; i < (int) EquipmentRarity::count; i++) {
				for (int j = 0; j < 3; j++) {
					int minNum = 0;
					int maxNum = *(arrQuantity[i]);
					if (j == 2) {
						minNum = maxNum;
					}

					pair<string, int> ret = createEquipment(equipmentType, arrRarity[i], minNum, maxNum);
					equipmentsName.push_back(ret.first);
					equipmentsQuantity.push_back(ret.second);

					*(arrQuantity[i]) -= ret.second;
					if (*(arrQuantity[i]) <= 0) {
						break;
					}
				}
			}

			break;
		}
		default:
			break;
	}


}

void ShopScene::onRecharge(CCObject *sender) {
	GoldCoinScene *scene = GoldCoinScene::create();
	CCDirector::sharedDirector()->pushScene(scene);
}

void ShopScene::onEnter() {
	CCScene::onEnter();

	sprintf(buf, "%d", GDM->money);
	_labelMoney->setString(buf);

	CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, -1, true);
	CCDirector::sharedDirector()->getKeypadDispatcher()->addDelegate(this);
}

pair<string, int> ShopScene::createEquipment(EquipmentType type, EquipmentRarity rarity, int minNum, int maxNum) {
	pair<string, int> ret;

	vector<string> arr = GDM->getEquipmentsNames(type, rarity);

	int index = rand() % arr.size();
	ret.first = arr[index];
	if (minNum == maxNum) {
		ret.second = minNum;
	} else {
		ret.second = rand() % maxNum;
	}

	return ret;
}

void ShopScene::showViewOfEquipmentBought(const vector<EquipmentInfo>& items) {
	CCLayerColor *maskLayer = CCLayerColor::create(ccc4(0, 0, 0, 128));
	maskLayer->setContentSize(_layer->getContentSize());
	maskLayer->setPosition(CCPointZero);
	maskLayer->setAnchorPoint(CCPointZero);
	maskLayer->setTag(TAG_MASK_LAYER);
	_layer->addChild(maskLayer);

	CCSize bgSize = CCSizeMake(450 * GM->minscale, 380 * GM->minscale);
	auto viewBg = cocos2d::extension::CCScale9Sprite::create("textures/pad_bg.png", CCRectMake(0, 0, 225, 225), CCRectMake(100, 100, 25, 25));
	viewBg->setContentSize(bgSize);
	viewBg->setPosition(ccp(GM->screenSize.width / 2, GM->screenSize.height / 2));
	viewBg->setAnchorPoint(ccp(0.5f, 0.5f));
	maskLayer->addChild(viewBg);

	float left_margin = 65;
	float x = left_margin;
	float y = 248;
	for (size_t i = 0; i < items.size(); i++) {
		EquipmentInfo info = items[i];

		CCSprite *itemFrame = MAKE_SPRITE("equipment_pad.png");
		itemFrame->setPosition(ccp(x, y));
		viewBg->addChild(itemFrame);

		if (info.rarity != EquipmentRarity::common) {
			sprintf(buf, "rarity_color_%s.png", RARITY_NAMES[(int) info.rarity]);
			CCSprite *itemRarityBg = MAKE_SPRITE(buf);
			itemRarityBg->setPosition(ccp(itemFrame->getContentSize().width / 2, itemFrame->getContentSize().height / 2));
			itemFrame->addChild(itemRarityBg);
		}

		string iconFile = GDM->getEquipmentIconFileName((EquipmentType) i, info.name);
		CCSprite *spr = MAKE_SPRITE(iconFile);
		spr->setScale(scales[i]);
		spr->setPosition(ccp(itemFrame->getContentSize().width / 2, itemFrame->getContentSize().height / 2));
		itemFrame->addChild(spr);

		CCSprite *sprQuantityPad = MAKE_SPRITE("quantity_pad.png");
		sprQuantityPad->setScale(1.0f);
		sprQuantityPad->setPosition(ccp(itemFrame->getContentSize().width, 0));
		sprQuantityPad->setAnchorPoint(ccp(1.0f, 0.0f));
		itemFrame->addChild(sprQuantityPad);

		sprintf(buf, "%d", info.quantity);
		CCLabelTTF *labelQuantity = CCLabelTTF::create(buf, "", 12);
		labelQuantity->setPosition(ccp(sprQuantityPad->getContentSize().width / 2, sprQuantityPad->getContentSize().height / 2));
		labelQuantity->setAnchorPoint(ccp(0.5f, 0.5f));
		sprQuantityPad->addChild(labelQuantity);

		x += left_margin;

		if (i > 0 && (i % 5 == 0)) {
			x = EQUIPMENT_ITEM_WIDTH / 2;
			y += PACK_HEIGHT + EQUIPMENT_ITEM_SPACE;
		}
	}

	auto button = RM->makeButton("button/button.png", nullptr, nullptr, this, menu_selector(ShopScene::onCloseViewOfEquipmentBought), viewBg);
	button->setPosition(ccp(218, 50));

	CCLabelTTF *labelClose = CCLabelTTF::create("Close", "", 20);
	labelClose->setPosition(ccp(button->getContentSize().width / 2.0f, button->getContentSize().height / 2.0f));
	labelClose->setAnchorPoint(ccp(0.5f, 0.5f));
	button->addChild(labelClose);
}

void ShopScene::onCloseViewOfEquipmentBought(CCObject *sender) {
	_layer->getChildByTag(TAG_MASK_LAYER)->removeFromParent();
}

void ShopScene::onExit() {
	CCScene::onExit();

	CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
	CCDirector::sharedDirector()->getKeypadDispatcher()->removeDelegate(this);
}
